package com.heiye.count.biz.consumer;

import com.heiye.count.biz.constants.MQConstants;
import com.heiye.count.biz.constants.RedisKeyConstants;
import com.heiye.count.biz.domain.mapper.UserCountDOMapper;
import com.heiye.count.biz.model.dto.QuizOperateMqDTO;
import com.heiye.framework.common.util.JsonUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author: heiye
 * @date: 2025/05/09 下午5:32
 * @version: v1.0.0
 * @description: 计数: 问题发布数
 */
@Component
@RocketMQMessageListener(
        // Group 组
        consumerGroup = "interact_group_" + MQConstants.TOPIC_QUIZ_OPERATE,
        // 主题 Topic
        topic = MQConstants.TOPIC_QUIZ_OPERATE
)
@Slf4j
public class CountQuizPublishConsumer implements RocketMQListener<Message> {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private UserCountDOMapper userCountDOMapper;

    @Override
    public void onMessage(Message message) {
        // 消息体
        String bodyJsonStr = new String(message.getBody());
        // 标签
        String tags = message.getTags();

        log.info("==> CountQuizPublishConsumer 消费了消息 {}, tags: {}", bodyJsonStr, tags);

        // 根据 MQ 标签，判断问题操作类型
        // 问题发送
        if (Objects.equals(tags, MQConstants.TAG_QUIZ_PUBLISH)) {
            handleTagMessage(bodyJsonStr, 1);
        }
        // 问题删除
        else if (Objects.equals(tags, MQConstants.TAG_QUIZ_DELETE)) {
            handleTagMessage(bodyJsonStr, -1);
        }
    }

    /**
     * 问题发布、删除
     *
     * @param bodyJsonStr
     */
    private void handleTagMessage(String bodyJsonStr, long count) {
        // 消息体 JSON 字符串转 DTO
        QuizOperateMqDTO quizOperateMqDTO = JsonUtils.parseObject(bodyJsonStr, QuizOperateMqDTO.class);

        if (Objects.isNull(quizOperateMqDTO)) {
            return;
        }
        // 问题发布者 ID
        Long creatorId = quizOperateMqDTO.getCreatorId();

        // 更新 Redis 中用户维度的计数 hash
        String countUserRedisKey = RedisKeyConstants.buildCountUserKey(creatorId);
        // 判断 Redis 中 hash 是否存在
        Boolean isCountUserExisted = redisTemplate.hasKey(countUserRedisKey);

        // 若存在才会更新
        // (因为缓存设有过期时间，考虑到过期后，缓存会被删除，这里需要判断一下，存在才会去更新，而初始化工作放在查询计数来做)
        if (isCountUserExisted) {
            // 对目标用户  Hash 中的问题发布总数，进行加减操作
            redisTemplate.opsForHash().increment(countUserRedisKey, RedisKeyConstants.FIELD_QUIZ_TOTAL, count);
        }

        // 更新 t_user_count 表
        userCountDOMapper.insertOrUpdateQuizTotalByUserId(count, creatorId);
    }

}
